<template>
  <div class="valueTree" v-if="integrationFilter">
    <!-- 递归组件区域 -->
    <div class="total_screen_show" v-if="recursion==='true'">
      <div class="left">
        <span class="tree_line"></span>
        <span
          class="tree_btn no_copy"
          @click="relationChange(filter.relation)"
        >{{filter.relation === 'AND' ? '且' :'或'}}</span>
      </div>
      <div class="right">
        <template v-for="(_is,_ins) in integrationFilter.newChildren">
          <valueTree
            :fieldArr="fieldArrEnter"
            :key="_ins+'valueTree'"
            :filter="_is"
            :limit="limit"
            :del="del"
            :delIcon="delIcon"
            :add="add"
            :addIcon="addIcon"
            :deep="deep"
            :deepIcon="deepIcon"
            :groupWrite="groupWrite"
            :groupWriteIcon="groupWriteIcon"
          ></valueTree>
        </template>
      </div>
    </div>
    <!-- 单条渲染区域 -->
    <template v-if="recursion==='false'">
      <div class="valueTreeOne">
        <dropdownTriggerLayered
          class="field"
          :group="true"
          @change="oneChange"
          :promptPanel="true"
          :activeItemEnter="integrationFilter.field"
          :overallScreeningData="fieldArrEnter"
        ></dropdownTriggerLayered>
        <el-select
          @change="twoChange"
          class="fun"
          v-model="integrationFilter.function"
          placeholder="逻辑"
          size="small"
        >
          <el-option
            v-for="item in funarrChange(integrationFilter.field.dataType)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <!-- 有值 无值  -->
        <template
          v-if="integrationFilter.function == 'equal' || integrationFilter.function == 'notEqual'"
        >
          <el-select
            v-model="integrationFilter.params"
            size="small"
            :popper-append-to-body="false"
            class="paramsArr"
            multiple
            :no-data-text="valueTxt"
            @visible-change="threeChange($event)"
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              allow-create
              v-for="item in paramsArrChoose"
              :key="item.itemValue"
              :label="item.itemKey"
              :value="item.itemValue"
            >
              <el-popover
                v-if="item.itemKey.length >= 30"
                placement="top-start"
                width="600"
                trigger="hover"
              >
                <p>{{ item.itemKey }}</p>
                <span slot="reference">{{ item.itemKey.slice(0,29) + '...' }}</span>
              </el-popover>
              <span v-else>{{ item.itemKey }}</span>
            </el-option>
          </el-select>
        </template>
        <!-- 区间 -->
        <template v-if="integrationFilter.function == 'between'">
          <el-input
            type="number"
            size="small"
            @change="btmblur"
            class="paramsDung"
            v-model="integrationFilter.params[0]"
            placeholder="请输入内容"
          ></el-input>
          <span class="paramsDungTxt">至</span>
          <el-input
            type="number"
            size="small"
            class="paramsDung"
            @change="btmblur"
            v-model="integrationFilter.params[1]"
            placeholder="请输入内容"
          ></el-input>
        </template>

        <!-- 删除功能 -->
        <span
          class="tools_one err"
          @click="$parent.valueTreeChange(integrationFilter.grade,integrationFilter.uniqueIdentification,'del')"
          v-if="del||delIcon"
        >
          <i :class="delIcon" v-if="delIcon"></i>
          <span v-if="del">{{del}}</span>
        </span>
        <!-- 批量录入功能 -->
        <!-- <template v-if="integrationFilter.function == 1 || integrationFilter.function ==2">
          <span @click="dialogFormVisible=true" class="tools_one" v-if="groupWrite||groupWriteIcon">
            <i :class="groupWriteIcon" v-if="groupWriteIcon"></i>
            <span v-if="groupWrite">{{groupWrite}}</span>
          </span>
        </template>-->
        <!-- 判断是否传入下陷符 -->
        <template v-if="deep||deepIcon">
          <!-- 下陷功能 -->
          <span
            v-if="filter.grade<=limit"
            @click="$parent.valueTreeChange(integrationFilter.grade,integrationFilter.uniqueIdentification,'deep')"
            class="tools_one"
          >
            <i :class="deepIcon?deepIcon:'el-icon-bottom-left'"></i>
            <span v-if="deep">{{deep}}</span>
          </span>
          <!-- 新增功能 -->
          <span
            @click="$parent.valueTreeChange(integrationFilter.grade,integrationFilter.uniqueIdentification,'add')"
            class="tools_one"
            v-if="add||addIcon"
          >
            <i v-if="addIcon" :class="addIcon"></i>
            <span v-if="add">{{add}}</span>
          </span>
        </template>
        <template v-else>
          <span
            @click="noDeep(integrationFilter.grade,integrationFilter.uniqueIdentification)"
            class="tools_one"
            v-if="add || addIcon"
          >
            <i :class="addIcon" v-if="addIcon"></i>
            <span v-if="add">{{add}}</span>
          </span>
        </template>
      </div>
      <!-- 批量录入弹框 -->
      <!-- <el-dialog
        title="等于"
        width="30%"
        :modal-append-to-body="false"
        :modal="true"
        :visible.sync="dialogFormVisible"
      >
        <el-form>
          <el-form-item label="注意：按换行符分隔，每行一个值">
            <el-input type="textarea" v-model="textarea" :rows="12" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>-->
    </template>
  </div>
</template>

<script>
import dropdownTriggerLayered from "@/components/dropdownTriggerLayered/index.vue";
import analysisApi from "@/utils/api/analysisApi.js";
export default {
  name: "valueTree",
  components: { dropdownTriggerLayered },
  props: [
    "filter",
    "limit",
    "del",
    "delIcon",
    "add",
    "addIcon",
    "deep",
    "deepIcon",
    "groupWrite",
    "groupWriteIcon",
    "fieldArr"
  ],
  data: function() {
    return {
      valueTxt: "加载中。。。",
      paramsArrChoose: [], // 第三列可选值
      fieldArrEnter: [], // 第一列可选值
      textarea: "", // 批量录入弹框
      dialogFormVisible: false, // 批量录入弹框
      integrationFilter: null, // 数据结构整合后的筛选条件
      recursion: "Undefined" // 判断是否进行组件递归
    };
  },
  methods: {
    // 第一列更改数值
    async oneChange(value) {
      this.integrationFilter.field = value;
      // 字典类型，更改第三列可选值
      // let res = await analysisApi.eventAnalysis.metaPropertyDictionaryList({
      //   propertyType: String(value.properType),
      //   propertyId: value.propertyId
      // });
      // if (res&&res.success) {
      //   this.paramsArrChoose = res.value.list;
      // }
      let arr = this.funarrChange(this.integrationFilter.field.dataType);
      let bool = false;
      arr.map(_i => {
        if (_i.value == this.integrationFilter.function) {
          bool = true;
        }
      });
      if (!bool) {
        this.integrationFilter.function = null;
        this.integrationFilter.params = [];
      }
      this.valueTreeChange(
        this.integrationFilter.grade,
        this.integrationFilter.uniqueIdentification,
        "value",
        this.integrationFilter
      );
    },
    // 第二列更改
    twoChange(value) {
      // 区间逻辑
      if (value == "between") {
        this.integrationFilter.params = [0, 0];
      }
      // 真假有无值逻辑
      if (
        value == "isSet" ||
        value == "notSet" ||
        value == "isTrue" ||
        value == "isFalse"
      ) {
        this.integrationFilter.params = [];
      }

      // 等于 不等于 逻辑
      if (value == "equal" || value == "notEqual") {
        this.integrationFilter.params = [];
      }

      this.valueTreeChange(
        this.integrationFilter.grade,
        this.integrationFilter.uniqueIdentification,
        "value",
        this.integrationFilter
      );
    },
    // 第三列区间 光标失去事件
    btmblur() {
      // console.log( this.integrationFilter.params,'8888')
      let min = 0,
        max = 0;
      if (this.integrationFilter.params[0]) {
        min = Number(this.integrationFilter.params[0]);
      }
      if (this.integrationFilter.params[1]) {
        max = Number(this.integrationFilter.params[1]);
      }
      max = Number(max) <= Number(min) ? min : max;
      this.integrationFilter.params = [min, max];
      this.valueTreeChange(
        this.integrationFilter.grade,
        this.integrationFilter.uniqueIdentification,
        "value",
        this.integrationFilter
      );
    },
    // 第三列更改
    async threeChange(v) {
      if (!v) {
        this.valueTreeChange(
          this.integrationFilter.grade,
          this.integrationFilter.uniqueIdentification,
          "value",
          this.integrationFilter
        );
      }
      let res;
      if (
        this.integrationFilter &&
        this.integrationFilter.field &&
        this.integrationFilter.field.propertyId &&
        this.paramsArrChoose.length == 0 &&
        v
      ) {
        this.valueTxt = "加载中。。。";
        res = await analysisApi.eventAnalysis.metaPropertyDictionaryList({
          appId: this.appId,
          propertyType: String(this.integrationFilter.field.properType),
          propertyId: this.integrationFilter.field.propertyKey
        });
        if (res && res.success && res.value.list && res.value.list.length > 0) {
          // 对时间字段查询出来的字典列表进行加工处理
          if (this.integrationFilter.field.propertyId == "time") {
            res.value.list.map(_i=>{
            	let date = new Date(Number(_i.itemKey)); //获取一个时间对象
            	let year = date.getFullYear(); // 获取完整的年份(4位,1970)
            	let mon = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
            	mon = mon < 10 ? "0" + mon : mon;
            	let day = date.getDate(); // 获取日(1-31)
            	day = day < 10 ? "0" + day : day;
            	let hour = date.getHours();
            	let min = date.getMinutes();
            	let sec = date.getSeconds();
            	let itemKey = year + "年" + mon + "月" + day + "日" + hour + "时" + min + "分" + sec + "秒";
            	_i.itemKey = itemKey;
            })
          }
          this.paramsArrChoose = res.value.list;
        } else {
          this.valueTxt = "暂无数据";
        }
      }
    },
    // 第二列可选值更改
    funarrChange(str) {
      let _arr = [];
      switch (str) {
        case "字符串":
          _arr = [
            {
              label: "等于",
              value: "equal"
            },
            {
              label: "不等于",
              value: "notEqual"
            },
            {
              label: "有值",
              value: "isSet"
            },
            {
              label: "无值",
              value: "notSet"
            }
          ];
          break;
        case "STRING":
          _arr = [
            {
              label: "等于",
              value: "equal"
            },
            {
              label: "不等于",
              value: "notEqual"
            },
            {
              label: "有值",
              value: "isSet"
            },
            {
              label: "无值",
              value: "notSet"
            }
          ];
          break;
        case "数值":
          _arr = [
            {
              label: "等于",
              value: "equal"
            },
            {
              label: "不等于",
              value: "notEqual"
            },
            {
              label: "有值",
              value: "isSet"
            },
            {
              label: "无值",
              value: "notSet"
            },
            {
              label: "区间",
              value: "between"
            }
          ];
          break;
        case "NUMBER":
          _arr = [
            {
              label: "等于",
              value: "equal"
            },
            {
              label: "不等于",
              value: "notEqual"
            },
            {
              label: "有值",
              value: "isSet"
            },
            {
              label: "无值",
              value: "notSet"
            },
            {
              label: "区间",
              value: "between"
            }
          ];
          break;
        case "布尔":
          _arr = [
            {
              label: "为真",
              value: "isTrue"
            },
            {
              label: "为假",
              value: "isFalse"
            }
          ];
          break;
        case "BOOL":
          _arr = [
            {
              label: "为真",
              value: "isTrue"
            },
            {
              label: "为假",
              value: "isFalse"
            }
          ];
          break;
        default:
          _arr = [];
      }
      return _arr;
    },
    // 数据整合函数
    dataRestructure(obj) {
      let _obj = {};
      let _arr = [];
      let that = this;
      try {
        if (Array.isArray(obj.filters)) {
          obj.filters.map(_i => {
            _arr.push(_i);
          });
        }
        if (Array.isArray(obj.conditions)) {
          obj.conditions.map(_i => {
            _arr.push(_i);
          });
        }
        if (_arr.length > 1) {
          // 根据render_index进行排序
          _arr.sort((a, b) => {
            return parseInt(a.render_index) - parseInt(b.render_index);
          });
          _obj = {
            uniqueIdentification: JSON.parse(
              JSON.stringify(obj.uniqueIdentification)
            ),
            grade: JSON.parse(JSON.stringify(obj.grade)),
            relation: JSON.parse(JSON.stringify(obj.relation)),
            render_index: JSON.parse(JSON.stringify(obj.render_index)),
            newChildren: JSON.parse(JSON.stringify([..._arr]))
          };
          that.recursion = "true";
        } else if (_arr.length == 1) {
          _obj = {
            uniqueIdentification: JSON.parse(
              JSON.stringify(_arr[0].uniqueIdentification)
            ),
            grade: JSON.parse(JSON.stringify(_arr[0].grade)),
            render_index: JSON.parse(JSON.stringify(_arr[0].render_index)),
            field: JSON.parse(JSON.stringify(_arr[0].field)),
            function: JSON.parse(JSON.stringify(_arr[0].function)),
            params: JSON.parse(JSON.stringify(_arr[0].params))
          };
          that.recursion = "false";
        } else {
          _obj = {
            uniqueIdentification: JSON.parse(
              JSON.stringify(obj.uniqueIdentification)
            ),
            grade: JSON.parse(JSON.stringify(obj.grade)),
            render_index: JSON.parse(JSON.stringify(obj.render_index)),
            field: JSON.parse(JSON.stringify(obj.field)),
            function: JSON.parse(JSON.stringify(obj.function)),
            params: JSON.parse(JSON.stringify(obj.params))
          };
          that.recursion = "false";
        }
      } catch (err) {
        this.$message({
          message: err,
          type: "warning"
        });
      }
      return _obj;
    },
    // 参数一：层级  参数二：标识符  参数三：处理方式
    valueTreeChange(grade, uniqueIdentification, type, newValue = null) {
      this.$parent.valueTreeChange(grade, uniqueIdentification, type, newValue);
    },
    relationChange(relation) {
      let str = relation === "AND" ? "OR" : "AND";
      this.$parent.valueTreeChange(
        this.filter.grade,
        this.filter.uniqueIdentification,
        "relation",
        str
      );
    },
    // 未传入下陷图标的新增函数
    noDeep(grade, key) {
      let type = "add";
      if (grade <= this.limit) {
        type = "deep";
      }
      this.$parent.valueTreeChange(grade, key, type);
    }
  },
  watch: {},
  beforeCreate() {},
  async created() {
    this.integrationFilter = JSON.parse(
      JSON.stringify(this.dataRestructure(this.filter))
	);
	this.fieldArrEnter = JSON.parse(JSON.stringify(this.fieldArr));
  },
  beforeMount() {},
  mounted() {
  },
  computed: {
    appId() {
      return this.$store.state.global.appId;
    }
  }
};
</script>

<style scoped lang='scss'>
.field {
  margin-right: 0.2rem;
}
.fun {
  width: 1.4rem;
  margin-right: 0.2rem;
}
.paramsArr {
  min-width: 5rem;
  margin-right: 0.2rem;
}
.paramsDan {
  margin-right: 0.2rem;
  width: 4rem;
}
.paramsDung {
  margin-right: 0.2rem;
  width: 2rem;
}
.paramsDungTxt {
  margin-right: 0.2rem;
}
.total_screen_show {
  width: 100%;
  box-sizing: border-box;
  position: relative;
  .left {
    height: 100%;
    width: 1rem;
    position: absolute;
    .tree_line {
      position: absolute;
      border-left: 1px solid #dcdfe6;
      top: 6px;
      bottom: 6px;
      left: 0.5rem;
    }
    .tree_btn {
      position: absolute;
      left: 50%;
      top: 50%;
      padding: 6px 4px;
      font-size: 10px;
      border-radius: 4px;
      background: #dcdfe6;
      transform: translate(-50%, -50%);
    }
    .tree_btn:hover {
      background: rgba($color: #01b27a, $alpha: 1);
      color: rgba($color: white, $alpha: 0.9);
    }
  }
  .right {
    width: calc(100% - 80px);
    margin-left: 80px;
    box-sizing: border-box;
  }
}
.valueTreeOne {
  height: 0.6rem;
  display: flex;
  align-items: center;
  ::v-deep .el-tag {
    max-width: 80px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
// 级联样式
.valueTreeOne {
  display: flex;
  align-items: center;
  border-radius: 4px;
  min-height: 46px;
  i {
    font-weight: 800;
    opacity: 0;
    margin: 0 0.05rem 0 0;
  }
  .tools_one {
    margin: 0 0.3rem 0 0;
    opacity: 0;
  }
  .tools_one:hover {
    color: #007aff;
    font-weight: 500;
  }
  .err:hover {
    color: red;
    // font-size: 16px;
  }
}
.valueTreeOne:hover {
  // background: rgba($color: #f2f6fc, $alpha: 1);
  background: rgba($color: #409eff, $alpha: 0.2);
  i,
  .tools_one {
    opacity: 1;
  }
}
</style>
